package cn.zhangfusheng.elasticsearch.model.es;

import cn.zhangfusheng.elasticsearch.constant.enumeration.RangeKeyword;
import cn.zhangfusheng.elasticsearch.exception.GlobalSystemException;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;

import java.util.Objects;

/**
 * @author fusheng.zhang
 * @date 2022-04-26 17:25:52
 */
@Data
@AllArgsConstructor
public class EsRange {

    /**
     * 左侧关键字
     */
    private RangeKeyword leftKeyword;

    /**
     * 左侧对应的值
     */
    private Object leftValue;

    /**
     * 右侧关键字
     */
    private RangeKeyword rightKeyword;

    /**
     * 右侧对应的值
     */
    private Object rightValue;

    private String fromat;

    private Boolean includeLower;
    private Boolean includeUpper;

    public QueryBuilder builder(RangeQueryBuilder rangeQueryBuilder) {
        if (Objects.isNull(this.rightValue) || Objects.isNull(this.leftValue)) {
            throw new GlobalSystemException("left value or right value is null");
        }
        if (Objects.nonNull(this.rightKeyword) && Objects.nonNull(this.leftKeyword)) {
            this.rightKeyword.getBuilder(this.rightValue, rangeQueryBuilder);
            this.leftKeyword.getBuilder(this.leftValue, rangeQueryBuilder);
        } else {
            rangeQueryBuilder.from(this.leftValue).to(this.rightValue);
        }
        if (StringUtils.isNotBlank(fromat)) rangeQueryBuilder.format(fromat);
        if (Objects.nonNull(includeLower)) rangeQueryBuilder.includeLower(includeLower);
        if (Objects.nonNull(includeUpper)) rangeQueryBuilder.includeUpper(includeUpper);
        return rangeQueryBuilder;
    }
}
